package com.lingnan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.dto.JobPositionDto;
import com.lingnan.entity.po.JobApplication;
import com.lingnan.entity.po.JobPosition;
import com.lingnan.entity.po.Resume;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.JobPositionFeignClient;
import com.lingnan.mapper.ResumeMapper;
import com.lingnan.service.JobApplicationService;
import com.lingnan.service.ResumeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements ResumeService {

    @Autowired
    private ResumeMapper resumeMapper;

    @Autowired
    private JobApplicationService jobApplicationService;

    @Autowired
    private JobPositionFeignClient jobPositionFeignClient;

    @Override
    public List<JobPositionDto> getlist(Integer seekId, Integer status) {
        // 根据seekId查询所有投递记录
        List<JobApplication> jobApplications = jobApplicationService.getJobApplicationById(Long.valueOf(seekId));

        // 如果传入了status参数，则根据status过滤投递记录
        if (status != null) {
            jobApplications = jobApplications.stream()
                    .filter(application -> application.getStatus().equals(Long.valueOf(status)))
                    .collect(Collectors.toList());
        }

        // 拿到过滤后的投递记录的positionId列表
        List<Long> positionIds = jobApplications.stream()
                .map(JobApplication::getPositionId)
                .collect(Collectors.toList());

        // 如果没有符合条件的投递记录，直接返回空列表
        if (positionIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 根据positionId列表查询职位信息
        Result<List<JobPosition>> data = jobPositionFeignClient.getJobPositionByIds(positionIds);
        List<JobPosition> jobPositions = data.getData();

        // 将JobApplication列表转换为Map，以positionId为key
        Map<Long, JobApplication> applicationMap = jobApplications.stream()
                .collect(Collectors.toMap(JobApplication::getPositionId, Function.identity()));

        // 合并成JobPositionDto列表
        return jobPositions.stream().map(position -> {
            JobPositionDto dto = new JobPositionDto();

            // 使用BeanUtils复制属性
            BeanUtils.copyProperties(position, dto);

            // 设置对应的JobApplication
            dto.setJobApplication(applicationMap.get(position.getId()));

            return dto;
        }).collect(Collectors.toList());
    }


}